/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.registry;

import picounit.Registry;
import picounit.Registry.ImplementationCapturer;

import java.util.List;

public class FactoryRegistryEntry<B> implements RegistryEntry {
	private final Class<B> baseClass;
	private final List<Object> implementationsAndInstances;

	public FactoryRegistryEntry(Class<B> baseClass, List<Object> implementationsAndInstances) {
		this.baseClass = baseClass;
		this.implementationsAndInstances = implementationsAndInstances;
	}

	@SuppressWarnings("unchecked")
	public void registerWith(Registry registry) {
		ImplementationCapturer<B> implementationCapturer = registry.registerFactory(baseClass);

		for (Object implementationOrInstance : implementationsAndInstances) {
			if (baseClass.isInstance(implementationOrInstance)) {
				implementationCapturer = implementationCapturer.add(baseClass.cast(implementationOrInstance));
			}
			else {
				implementationCapturer = implementationCapturer.add((Class<B>) implementationOrInstance);
			}
		}
	}
}
